package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.TeacherDao;
import com.example.data.request.ReqTeacherList;
import com.example.data.response.RespTeacherInfo;
import com.example.entity.Teacher;
import com.example.service.TeacherService;
import com.example.utils.BCrypt;
import com.example.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:yanghua
 * Date:2023/10/8 8:30
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherDao, Teacher> implements TeacherService {
    @Resource
    private TeacherDao teacherDao;

    @Override
    public R addTeacher(Teacher teacher) {
        teacher.setPassword(BCrypt.hashpw(teacher.getPassword(), BCrypt.gensalt())); // 密码加密
        List<Teacher> allTeachers = teacherDao.getAllTeachers();
        for (Teacher t : allTeachers) {
            if (t.getNumId().equals(teacher.getNumId())) {
                return R.error("已存在该老师！");
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("info", teacher);
        int i = teacherDao.insert(teacher);
        return i == 1 ? R.ok(data,"添加成功") : R.error("添加失败");
    }

    @Override
    public R deleteTeacher(Long id) {
        Integer i = teacherDao.deleteTeacher(id);
        return i == 1 ? R.ok("删除成功") : R.error("删除失败");
    }

    @Override
    public R updateTeacher(Teacher teacher) {
        teacher.setPassword(BCrypt.hashpw(teacher.getPassword(), BCrypt.gensalt()));
        int i = teacherDao.updateById(teacher);
        Map<String, Object> data = new HashMap<>();
        data.put("info", teacher);
        return i == 1 ? R.ok(data,"修改成功") : R.error("修改失败");
    }

    @Override
    public R getTeacherList(ReqTeacherList reqTeacherList) {
        reqTeacherList.setPage((reqTeacherList.getPage() - 1) * reqTeacherList.getSize());
        List<RespTeacherInfo> teacherList = teacherDao.getTeacherList(reqTeacherList);
        Integer number = teacherDao.getTeacherNum(reqTeacherList);
        Map<String, Object> data = new HashMap<>();
        data.put("list", teacherList);
        data.put("size", number);
        return R.ok(data, "查询成功");
    }
}
